import * as vscode from 'vscode'
import * as path from 'path'
import { DistBuildHostDefinition, DistBuildHostState } from './DistBuildDefintions'
import { DistBuildDataManager } from './DataManager';
import * as util from 'util'

export class DistBuildTreeItem extends vscode.TreeItem {
    constructor(
        public readonly label: string,
        public readonly collapsibleState: vscode.TreeItemCollapsibleState,
        public readonly command?: vscode.Command
    ) {
        super(label, collapsibleState);

        this.tooltip = `${this.label}`;
        this.description = this.label;
    }

}

export class DistBuildTreeView implements vscode.TreeDataProvider<DistBuildTreeItem> {
    static viewId = "distbuildtree"
    private _onDidChangeTreeData: vscode.EventEmitter<DistBuildTreeItem | undefined | void> = new vscode.EventEmitter<DistBuildTreeItem | undefined | void>();
    readonly onDidChangeTreeData: vscode.Event<void | DistBuildTreeItem | DistBuildTreeItem[] | null | undefined> | undefined = this._onDidChangeTreeData.event;

    constructor(private _context: vscode.ExtensionContext) {
    }
    refresh(): void {
        this._onDidChangeTreeData.fire();
    }

    getTreeItem(element: DistBuildTreeItem): vscode.TreeItem | Thenable<vscode.TreeItem> {
        return element;
    }
    getChildren(element?: DistBuildTreeItem | undefined): vscode.ProviderResult<DistBuildTreeItem[]> {
        let result: DistBuildTreeItem[] = []
        if (element) {
            let state = DistBuildDataManager.getInstance(this._context.extensionPath).getDistBuildState();
            for (let entry of state.entries()) {
                let address = entry[0]
                let files = entry[1]
                if (address === '' || address === undefined) {
                    return
                }
                files.forEach(file => {
                    if (file.filename === "") {
                        return
                    }
                    let label = file.filename
                    let maxlength = 50
                    if (label.length > maxlength) {
                        label = label.substring(0, 47) + "..."
                    } else {
                        for (let i = 0; i < 50 - file.filename.length; i++) {
                            label += " "
                        }
                    }
                    console.log(file.filename.length, label.length)
                    label += file.state
                    let item: DistBuildTreeItem = new DistBuildTreeItem(label, vscode.TreeItemCollapsibleState.None)
                    item.contextValue = 'distbuild.state';
                    item.description = ''
                    result.push(item);
                })
            }
            /*
            state.forEach(val => {
                if (element.label == val.address) {
                }
            })
            */
            if (result.length === 0) {
                let item: DistBuildTreeItem = new DistBuildTreeItem('当前没有活动任务', vscode.TreeItemCollapsibleState.None);
                item.contextValue = 'distbuild.state';
                item.description = ''
                result.push(item);
            }
        } else {//root
            let hosts = DistBuildDataManager.getInstance(this._context.extensionPath).getDistHosts();
            hosts?.forEach(val => {
                if (val.address === '' || val.address === undefined) {
                    return
                }
                let item: DistBuildTreeItem = new DistBuildTreeItem(val.address, vscode.TreeItemCollapsibleState.Expanded)
                //item.tooltip = "" + val.jobs;
                item.description = `并行${val.jobs}个任务`;
                item.contextValue = val.state === DistBuildHostState.RUN ? 'distbuild.host.state.run' : 'distbuild.host.state.stop'
                result.push(item);
            });
        }
        return Promise.resolve(result);
    }
    add() {
        const opt: vscode.InputBoxOptions = {
            placeHolder: '请输入编译机地址格式：{user}@{ip address}:{port}/{max jobs}',
            value: 'kylin@172.30.203.244:3632/8'
        }
        //console.log(this._context)
        //let extPath = this._context.extensionPath
        vscode.window.showInputBox(opt).then(host => {
            const opt1: vscode.InputBoxOptions = {
                placeHolder: '请输入编译机登录密码，我们需要部署编译环境',
                password: true,
                value: 'Ide#2022'
            }
            if (host === '' || host === undefined) {
                vscode.window.showErrorMessage('请输入合法的编译机地址');
                return
            }
            vscode.window.showInputBox(opt1).then(pass => {
                let user = host.substring(0, host.indexOf('@'));
                let ip = host.substring(host.indexOf('@') + 1, host.indexOf(':'));
                let port = host.substring(host.indexOf(':') + 1, host.indexOf('/'));
                let maxJobs = host.substring(host.indexOf('/') + 1);
                let hostObj: DistBuildHostDefinition = new DistBuildHostDefinition();

                hostObj.address = ip;
                hostObj.jobs = Number(maxJobs);
                hostObj.port = Number(port);

                DistBuildDataManager.getInstance(this._context.extensionPath).addDistHost(hostObj);
                this.refresh()
            })
        })
    }
    runTask() {
        vscode.commands.executeCommand('workbench.action.tasks.build')
    }
    remove(theNode: DistBuildTreeItem) {
        DistBuildDataManager.getInstance(this._context.extensionPath).removeDistHost(theNode.label);
        this.refresh()
    }
    run(theNode: DistBuildTreeItem) {
        DistBuildDataManager.getInstance(this._context.extensionPath).runDistHost(theNode.label);
        this.refresh()
    }
    stop(theNode: DistBuildTreeItem) {
        DistBuildDataManager.getInstance(this._context.extensionPath).stopDistHost(theNode.label);
        this.refresh()
    }

}